package com.watson;

import static com.watson.broadcast.SystemBroadCast.SCN_CUST_ACTION_SCODE;
import static com.watson.broadcast.SystemBroadCast.SCN_CUST_EX_SCODE;

import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.util.Log;

import com.android.scanner.impl.ReaderManager;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.SPCookieStore;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.lzy.okgo.model.HttpHeaders;
import com.watson.http.CommonHttpUtil;
import com.watson.http.HttpClient;
import com.watson.http.SSLSocketClient;
import com.watson.utils.LogUtils;
import com.watson.utils.SPUtils;
import com.watson.utils.StringUtils;

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import okhttp3.OkHttpClient;


public class MyApp extends Application {
    private static Application mContext;
    public static OnImportListener onImportListener;
    private ReaderManager readerManager;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        LogUtils.setIsDebug(false);
        CommonHttpUtil.init();
        //---------这里给出的是示例代码,告诉你可以这么传,实际使用的时候,根据需要传,不需要就不传-------------//
        HttpHeaders headers = new HttpHeaders();
        headers.put("Content-Type", "application/json");     //header不支持中文，不允许有特殊字符
        headers.put("dateType", "json");
        headers.put("charset", "UTF-8");
//      HttpParams params = new HttpParams();
//      params.put("dateType", "json"); //param支持中文,直接传,不要自己编码
//      params.put("charset", "UTF-8");
        //-----------------------------------------------------------------------------------//

        //构建OkHttpClient.Builder
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.sslSocketFactory(SSLSocketClient.getSSLSocketFactory());
        builder.hostnameVerifier(SSLSocketClient.getHostnameVerifier());

        //配置log打印级别
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
        //log打印级别，决定了log显示的详细程度
//        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.NONE);
        //log颜色级别，决定了log在控制台显示的颜色
        loggingInterceptor.setColorLevel(Level.INFO);
        builder.addInterceptor(loggingInterceptor);

        //全局的读取超时时间
        builder.readTimeout(HttpClient.TIMEOUT, TimeUnit.MILLISECONDS);
        //全局的写入超时时间
        builder.writeTimeout(HttpClient.TIMEOUT, TimeUnit.MILLISECONDS);
        //链接超时时间
        builder.connectTimeout(HttpClient.TIMEOUT, TimeUnit.MILLISECONDS);

        //使用sp保持cookie，如果cookie不过期，则一直有效
        builder.cookieJar(new CookieJarImpl(new SPCookieStore(this)));

        //以下设置的所有参数是全局参数,同样的参数可以在请求的时候再设置一遍,那么对于该请求来讲,请求中的参数会覆盖全局参数
        //好处是全局参数统一,特定请求可以特别定制参数
        try {
            OkGo.getInstance().init(this)//必须调用初始化

                    //以下都不是必须的，根据需要自行选择
                    .setOkHttpClient(builder.build())
                    //可以全局统一设置缓存模式,默认是不使用缓存,可以不传,具体其他模式看 github 介绍 https://github.com/jeasonlzy/
//                    .setCacheMode(CacheMode.NO_CACHE)
                    //可以全局统一设置缓存时间,默认永不过期,具体使用方法看 github 介绍
//                    .setCacheTime(7)
                    //可以全局统一设置超时重连次数,默认为三次,那么最差的情况会请求4次(一次原始请求,三次重连请求),不需要可以设置为0
                    .setRetryCount(2)
                    //这两行同上，不需要就不要加入
                    .addCommonHeaders(headers);   //设置全局公共头
//                    .addCommonParams(params);   //设置全局公共参数
        } catch (Exception e) {
            e.printStackTrace();
        }

        IntentFilter intentFilter = new IntentFilter(SCN_CUST_ACTION_SCODE);
        registerReceiver(scanDataReceiver, intentFilter);

        Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler(getContext()));

        init();
    }

    private static class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

        private Context context;

        public MyUncaughtExceptionHandler(Context context) {
            this.context = context;
        }

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            LogUtils.e("TAG", "e.getMessage():" + e.getMessage());
            LogUtils.e("TAG", "e.toString():" + e.toString());
            LogUtils.e("TAG", "e.getLocalizedMessage():" + e.getLocalizedMessage());

            SPUtils.put(getContext(), "benT", t.toString());
            SPUtils.put(getContext(), "benE", e.toString());
            SPUtils.put(getContext(), "benS", StringUtils.getTimeS());
        }
    }

    private void initScanner() {
        boolean isActive = readerManager.GetActive();
        if (!isActive) {
            readerManager.SetActive(true);
        }

        boolean enableScankey = readerManager.isEnableScankey();
        if (!enableScankey) {
            readerManager.setEnableScankey(true);
        }

        int outPutMode = readerManager.getOutPutMode();
        if (outPutMode != 2) {
            readerManager.setOutPutMode(2);
        }
    }

    public static Application getContext() {
        return mContext;
    }

    public BroadcastReceiver scanDataReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(SCN_CUST_ACTION_SCODE)) {
                try {
                    String message = "";
                    message = intent.getStringExtra(SCN_CUST_EX_SCODE);
                    if (readerManager != null) {
                        readerManager.stopScanAndDecode();
                    }

                    if (StringUtils.isFastClick()) {
                        return;
                    }

                    if (onImportListener != null) {
                        onImportListener.showToastMessage(message);
                    }
                    Log.d("ScanTest", "-------ScannerService----------message = " + message);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("ScannerService", e.toString());
                }
            }
        }
    };

    // 程序终止的时候执行
    @Override
    public void onTerminate() {
        if (readerManager != null) {
            unregisterReceiver(scanDataReceiver);
            readerManager.Release();
            readerManager = null;
        }
        super.onTerminate();
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
    }

    private void init() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (readerManager == null) {
                    readerManager = ReaderManager.getInstance();
                    initScanner();
                }
            }
        }, 3 * 1000);  // 延迟3秒执行
    }

    public static void setOnImportListener(OnImportListener listener) {
        onImportListener = listener;
    }

    public interface OnImportListener {
        void showToastMessage(String message);
    }
}
